import {messages, getQueryUrlParam} from "share/common";
import React from 'react'
import {connect} from "react-redux";
import { message, Icon, Form, Modal, Button, Row, Col, Input } from 'antd'
const FormItem = Form.Item;
const { TextArea } = Input;
import Chooser from 'components/chooser'
import 'styles/components/template/approve-transfer.scss'
import approveService from 'containers/approve/approve.service'

class ApproveTransfer extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    }
  }

  componentWillMount() {}

  componentWillReceiveProps(nextProps) {
    const { transferVisible, form } = this.props;
    if (!transferVisible && nextProps.transferVisible) {
      form.resetFields();
    }
  }

  //isSuccess 是否是成功的返回
  closeTransferModal = (isSuccess) => {
    const { onClose } = this.props;
    if (onClose) {
      onClose(isSuccess);
    }
  };

  //isTransmitFilter是否忽略提示信息，直接提交
  handleTransfer = (isTransmitFilter) => {
    const { entities } = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let params = {
          entities: [{
            approverOID: entities.approverOID,
            entityOID: entities.entityOID,
            entityType: entities.entityType
          }],
          transmitFilter: !!isTransmitFilter,
          transferrePersonOID: values.person[0].userOID,
          approvalTxt: values.reason
        };
        this.setState({loading: true});
        approveService.postApproveTransfer(params).then(res => {
          if (res && res.data) {
            if (res.data.failNum) {
              message.error(`${messages('common.operate.filed')}，${res.data.failReason[entities.entityOID]}`);
            } else {
              if (res.data.transmitWarning) {
                let content = res.data.transmitWarning;
                //可二次确认提交
                //弹框提示是否继续提交
                Modal.confirm({
                  title: messages('components.key951')/*转交确认*/,
                  content: (
                    <div style={{whiteSpace: 'pre-wrap'}} dangerouslySetInnerHTML={{__html: content}}></div>
                  ),
                  okText: messages('components.key947')/*转交*/,
                  cancelText: messages('common.cancel')/*取消*/,
                  onOk: () => this.handleTransfer(true),
                  onCancel: this.pureCancelSubmit
                });
              } else {
                //提交成功的处理
                message.success(messages('common.operate.success'));
                this.closeTransferModal(true);
              }
            }
          }
        }).catch(e => {
          let error = e.response.data;
          if (error.validationErrors && error.validationErrors.length) {
            message.error(`${error.validationErrors[0].message}`);
          } else {
            message.error(`${error.message}`);
          }
        }).finally(() => {
          this.setState({loading: false});
        });
      }
    });
  };

  //取消二次确认的转交
  pureCancelSubmit = () => {
    this.setState({loading: false});
  };

  render() {
    const { transferVisible, customFormPropertyMap } = this.props;
    const { loading } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
    };
    let signCompanyOIDs = (customFormPropertyMap && customFormPropertyMap['approval_add_sign_scope']) ? JSON.parse(customFormPropertyMap['approval_add_sign_scope']).companyOIDs : [];
    return (
      <div>
        <Modal
          className="approve-transfer"
          title={messages('request.key529')/*转交*/}
          visible={transferVisible}
          onCancel={() => this.closeTransferModal(false)}
          maskClosable={false}
          destroyOnClose={true}
          footer={[
            <Button key="back" onClick={() => this.closeTransferModal(false)}>{messages('common.cancel')/*取消*/}</Button>,
            <Button key="submit" type="primary" loading={loading} onClick={() => this.handleTransfer()}>{messages('components.key947')/*转交*/}</Button>
          ]}
        >
          <Form>
            <FormItem {...formItemLayout} label={messages('components.key952')/*选择要转交的员工*/}>
              {getFieldDecorator('person', {
                rules: [
                  {
                    required: true,
                    message: messages('common.please.select') //请选择
                  }
                ]
              })(
                <Chooser
                  placeholder={messages('components.key953')/*请选择员工（单选）*/}
                  type='user'
                  labelKey='fullName'
                  valueKey='userOID'
                  listExtraParams={{
                    roleType: 'TENANT',
                    corporationOID: signCompanyOIDs,
                    companyOID: signCompanyOIDs
                  }}
                  showNumber={false}
                  single={true}
                />
              )}
            </FormItem>
            <div className="description">{messages('components.key954')/*说明：自己不审批单据，交给指定员工进行审批。后续审批流程照常进行*/}</div>
            <FormItem {...formItemLayout} label={messages('components.key955')/*转交理由*/}>
              {getFieldDecorator('reason', {
                rules: [
                  {
                    required: true,
                    message: messages('common.please.enter') //请输入
                  },
                  {
                    max: 500,
                    message: messages('common.max.characters.length', {max: 500})
                  }
                ]
              })(
                <TextArea rows={4} placeholder={messages('components.key956')/*请说明理由*/} style={{resize: 'none'}} />
              )}
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
}

ApproveTransfer.propTypes = {
  transferVisible: React.PropTypes.bool,
  onClose: React.PropTypes.func,
  entities: React.PropTypes.object,//审批跳转所需字段
  customFormPropertyMap: React.PropTypes.object
};

ApproveTransfer.defaultProps = {
  transferVisible: false,
  onClose: () => {},
  entities: {},
  customFormPropertyMap: {}
};

function mapStateToProps(state) {
  return {}
}

const wrappedApproveTransfer = Form.create()(ApproveTransfer);
export default connect(mapStateToProps)(wrappedApproveTransfer);
